import json
from datetime import datetime
from typing import Dict, List
import os

class UserLogger:
    def __init__(self, log_dir: str = "logs", max_file_size: int = 1048576):  # 1MB
        self.log_dir = log_dir
        self.max_file_size = max_file_size
        self._ensure_log_dir()

    def _ensure_log_dir(self):
        """确保日志目录存在"""
        if not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir)

    def _get_current_log_file(self) -> str:
        """获取当前日志文件路径"""
        today = datetime.now().strftime("%Y-%m-%d")
        return os.path.join(self.log_dir, f"user_log_{today}.json")

    def _rotate_log_if_needed(self, file_path: str):
        """如果日志文件过大，进行轮转"""
        if os.path.exists(file_path) and os.path.getsize(file_path) >= self.max_file_size:
            timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
            new_path = file_path.replace(".json", f"_{timestamp}.json")
            os.rename(file_path, new_path)

    def log_action(self, user_id: str, action: str, details: Dict):
        """记录用户行为日志"""
        log_entry = {
            "timestamp": datetime.now().isoformat(),
            "user_id": user_id,
            "action": action,
            "details": details
        }
        
        log_file = self._get_current_log_file()
        self._rotate_log_if_needed(log_file)
        
        mode = "a" if os.path.exists(log_file) else "w"
        with open(log_file, mode, encoding="utf-8") as f:
            if mode == "a":
                f.write("\n")
            json.dump(log_entry, f, ensure_ascii=False)

    def query_logs(self, user_id: str = None, action: str = None, date: str = None) -> List[Dict]:
        """查询用户行为日志"""
        log_file = self._get_current_log_file() if date is None else os.path.join(self.log_dir, f"user_log_{date}.json")
        
        if not os.path.exists(log_file):
            return []

        logs = []
        with open(log_file, "r", encoding="utf-8") as f:
            for line in f:
                try:
                    log = json.loads(line.strip())
                    if (user_id is None or log["user_id"] == user_id) and \
                       (action is None or log["action"] == action):
                        logs.append(log)
                except json.JSONDecodeError:
                    continue
        return logs

if __name__ == "__main__":
    # 示例用法
    logger = UserLogger()
    
    # 记录一些日志
    logger.log_action("user123", "search", {"keyword": "猫粮", "results": 15})
    logger.log_action("user456", "purchase", {"product_id": 123, "amount": 99.9})
    
    # 查询日志
    logs = logger.query_logs(user_id="user123")
    print(json.dumps(logs, indent=2, ensure_ascii=False))
